package cn.kkcxy.blog.system.service.impl.sys;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.kkcxy.blog.common.constant.AuthRegexConstants;
import cn.kkcxy.blog.common.constant.ExceptionMessageConstant;
import cn.kkcxy.blog.common.constant.SysRoleConstants;
import cn.kkcxy.blog.common.properties.RegisterUserProperties;
import cn.kkcxy.blog.core.convert.RegisterArgumentsDTOConverter;
import cn.kkcxy.blog.core.dto.admin.ManageGetUserListDTO;
import cn.kkcxy.blog.core.dto.client.CheckUserAccountParamsDTO;
import cn.kkcxy.blog.core.entity.sys.SysRole;
import cn.kkcxy.blog.core.entity.sys.SysUser;
import cn.kkcxy.blog.core.exception.auth.SystemRoleException;
import cn.kkcxy.blog.core.exception.auth.UserAccountRegisterException;
import cn.kkcxy.blog.core.exception.common.MethodParameterException;
import cn.kkcxy.blog.core.vo.admin.system.SimpleUserInfoVO;
import cn.kkcxy.blog.core.vo.admin.system.UserDetailsVO;
import cn.kkcxy.blog.system.mapper.sys.SysUserMapper;
import cn.kkcxy.blog.system.service.sys.SysRoleService;
import cn.kkcxy.blog.system.service.sys.SysUserRoleService;
import cn.kkcxy.blog.system.service.sys.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @author kk
 * @description 针对表【sys_user】的数据库操作Service实现
 * @createDate 2024-09-11 00:50:27
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    /**
     * 系统用户mapper
     */
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 系统角色服务
     */
    @Resource
    private SysRoleService sysRoleService;

    /**
     * 系统用户角色关联服务
     */
    @Resource
    private SysUserRoleService sysUserRoleService;

    /**
     * 注册配置属性
     */
    @Resource
    private RegisterUserProperties registerUserProperties;

    /**
     * @description: 查询账号是否被禁用或删除
     * @author: kkcxy
     * @date: 2024/9/11 23:53
     * @param: [dto]
     * @return: cn.kkcxy.blog.core.entity.sys.SysUser
     **/
    @Override
    public SysUser selectUserAccountDisabled(CheckUserAccountParamsDTO dto) {
        // 如果参数为空 直接抛异常
        if (Objects.isNull(dto)) {
            if (log.isErrorEnabled()) {
                log.error("SysUserServiceImpl.selectUserAccountDisabled.error: {}", ExceptionMessageConstant.METHOD_PARAMETER_ERROR);
            }
            throw new MethodParameterException(ExceptionMessageConstant.METHOD_PARAMETER_ERROR);
        }
        return sysUserMapper.selectUserAccountDisabled(dto);
    }

    /**
     * @description: 用户注册
     * @author: kkcxy
     * @date: 2024/9/12 0:39
     * @param: [dto]
     * @return: SysUserPO
     **/
    @Override
    @Transactional
    public SysUser register(CheckUserAccountParamsDTO dto) {
        // 如果参数为空 直接抛异常
        if (Objects.isNull(dto)) {
            if (log.isErrorEnabled()) {
                log.error("SysUserServiceImpl.register.error: {}", ExceptionMessageConstant.METHOD_PARAMETER_ERROR);
            }
            throw new MethodParameterException(ExceptionMessageConstant.METHOD_PARAMETER_ERROR);
        }
        // 账号注册
        if (StringUtils.isNotEmpty(dto.getUsername()) && StringUtils.isNotEmpty(dto.getPassword())) {
            if (dto.getPassword().length() >= 20) {
                throw new UserAccountRegisterException(ExceptionMessageConstant.USER_ACCOUNT_LENGTH_MAX_ERROR);
            }
            dto.setPassword(SaSecureUtil.md5BySalt(dto.getPassword(), registerUserProperties.getSalt()));
        }
        // 邮箱注册 判断合法
        if (StringUtils.isNotEmpty(dto.getEmail())) {
            boolean matches = Pattern.matches(AuthRegexConstants.EMAIL_REGEX, dto.getEmail());
            if (!matches) throw new UserAccountRegisterException(ExceptionMessageConstant.EMAIL_ILLEGITIMATE_ERROR);
        }
        // 手机号注册 判断合法
        if (StringUtils.isNotEmpty(dto.getPhone())) {
            boolean matches = Pattern.matches(AuthRegexConstants.PHONE_REGEX, dto.getPhone());
            if (!matches) throw new UserAccountRegisterException(ExceptionMessageConstant.PHONE_ILLEGITIMATE_ERROR);
        }
        // mapstruct 转换数据参数
        SysUser sysUserPO = RegisterArgumentsDTOConverter.INSTANCE.convertAccountParamsTOSysUser(dto);
        // 注册完以后返回已注册的数据
        sysUserMapper.registerUser(sysUserPO);
        Long userId = sysUserPO.getId();
        // 判断是否数据插入成功
        if (userId == null) {
            throw new UserAccountRegisterException(ExceptionMessageConstant.USER_ACCOUNT_REGISTER_ERROR);
        }
        // 给用户分配角色
        SysRole role = sysRoleService.getRoleCodeByRoleId(SysRoleConstants.ROLE_NORMAL_USER);
        // 如果查询出来为空直接抛异常
        if (Objects.isNull(role)) {
            throw new SystemRoleException(ExceptionMessageConstant.SYSTEM_ROLE_CODE_NOT_FOUND);
        }
        // 将用户id 和 角色id 插入用户角色关系表中
        Boolean result = sysUserRoleService.saveUserRole(userId, role.getId());
        if (result) {
            throw new SystemRoleException(ExceptionMessageConstant.USER_GIVE_SYSTEM_ROLE_ERROR);
        }
        // 返回注册完的对象 以便工厂适配
        return sysUserMapper.selectById(userId);
    }

    /**
     * 得到用户简易信息列表
     */
    @Override
    public List<SimpleUserInfoVO> getSimpleUserInfoList(ManageGetUserListDTO manageGetUserListDTO) {
        return sysUserMapper.getSimpleUserInfoList(manageGetUserListDTO);
    }

    @Override
    public UserDetailsVO getUserDetails(String userId) {
        return sysUserMapper.getUserDetails(userId);
    }

}




